<?php
class CodeSpace_Oauth_Server_Request_Authorization extends CodeSpace_Oauth_Server_Request_Abstract
{
    protected $_authorizationURL = 'http://hal9000.services.mkb.com:41004/oauth/authorize';
    protected $_authorizationCallback = 'http://morpheus.gateway.mkb.com:41000/oauth/authorization';
    
    public function __construct($options = null)
    {
        parent::__construct($options);
    }
    
    public function process(CodeSpace_Oauth_Server $server)
    {
        $front = Zend_Controller_Front::getInstance();
        $request = $front->getRequest();
        
        if($request->getParam('callback', 'false') != "false")
        {
            // Callback Process
            
            $token = $request->getParam('token');
            $owner = $request->getParam('owner');
            
            // Making token authenticated
            $tokenTable = new Model_DbTable_Tokens();
            $rowSet = $tokenTable->find($token);
            if($rowSet->count() != 1)
            {
                throw new Exception('Invalid Request token for Authentication');
            }
            
            $tokenRow = $rowSet->current();
            $callback = $tokenRow->tkn_callback;
            $tokenRow->tkn_authenticated = true;
            $tokenRow->save();
            
            // Relating the Resource Owner and Token
            $ownerTable = new Model_DbTable_ResourceOwners();
            $resultSet = $ownerTable->find($token);
            foreach($resultSet as $row)
            {
                $row->delete();
            }
    
            $newRow = $ownerTable->createRow();
            $newRow->rown_token = $token;
            $newRow->rown_identification = $owner;
            $newRow->save();
            
            header('Location: ' . $callback);
            exit;
        }else
        {
            $token = $server->getToken();
        
            $requestParams = $server->prepareOauthParameters();
            $requestParams['token'] = $token->getToken();
            $requestParams['callback'] = $this->_authorizationCallback;
            
            $redirectUrl = $this->_authorizationURL . '?';
            $mergedParams = '';
            $counter = 1;
            foreach ($requestParams as $key => $value)
            {
                $mergedParams .= $key . '=' . $value;
                
                if($counter < count($requestParams))
                {
                    $mergedParams .= '&';    
                }
                
                $counter++;
            }
            
            header('Location: ' . $redirectUrl . $mergedParams);
            exit;
        }
    }
}
?>